//
//  ElectronicfenceVC.m
//  KEREN
//
//  Created by MW on 2023/4/6.
//

#import "ElectronicfenceVC.h"
#import "KRSettingCell.h"
#import "NewsSettingsCell.h"
@interface ElectronicfenceVC ()<UITableViewDelegate,UITableViewDataSource,MAMapViewDelegate>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSArray *titleArr;
@property(nonatomic, strong) MAMapView *mapView;
@property (nonatomic, copy) NSString *locationStr;
@property (nonatomic, assign) float lat;
@property (nonatomic, assign) float lng;
@property(nonatomic, strong) UIButton *rightButton;
@property (nonatomic, assign) BOOL isUpdateLocation;
@end

@implementation ElectronicfenceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"电子围栏"];
    _titleArr = @[@"围栏开关",@"围栏中心",@"围栏半径（公里）"];
    [self tableView];
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT - 200)];
    _mapView.delegate = self;
    _mapView.zoomLevel = 12;
    ///把地图添加至view
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    [self getDeviceSetting];
    self.tableView.tableFooterView = _mapView;
    [self getDeviceLocation];
}

- (void)getDeviceSetting{
    WEAKSELF
    NSDictionary *parameters = @{@"index":@(1),@"size":@(1),@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id)};
    [NetworkingTool POST:Device_setting parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        NSDictionary *dict = response[@"data"];
        weakSelf.setId = [dict[@"id"] intValue];
        weakSelf.setInfo = [DeviceSetInfo initWithDictionary:dict];
        NSDictionary *dictM = dict[@"ebike_set"][@"fence_center"];
        CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[dictM[@"lat"] floatValue] andLongitude:[dictM[@"lng"] floatValue]];
       // weakSelf.lat = [dictM[@"lat"] floatValue];
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = coor;
        //设置地图的定位中心点坐标
        weakSelf.mapView.centerCoordinate = coor;
        //将点添加到地图上，即所谓的大头针
        [weakSelf.mapView addAnnotation:pointAnnotation];
        if(!weakSelf.isUpdateLocation){
            [weakSelf setLocationWithLatitude:coor.latitude  AndLongitude:coor.longitude];
        }else{
            [self addLocation];
        }
        weakSelf.isUpdateLocation = NO;
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)getDeviceLocation{
    WEAKSELF
    [NetworkingTool POST:Device_location parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"cmd":@"Location"} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if([response[@"data"][@"lat"] floatValue] > 360){
                [[KRAlartManager shareInstance] showAlert:@"车辆位置获取失败"];
            }else{
                weakSelf.lat = [response[@"data"][@"lat"] floatValue];
                weakSelf.lng = [response[@"data"][@"lng"] floatValue];
            }
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:@"车辆位置获取失败"];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)addLocation{
    [self.mapView removeOverlays:self.mapView.overlays];
    CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:self.lat andLongitude:self.lng];
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];

    pointAnnotation.coordinate = coor;
    //设置地图的定位中心点坐标
    self.mapView.centerCoordinate = coor;
    //将点添加到地图上，即所谓的大头针
    [self setLocationWithLatitude:coor.latitude  AndLongitude:coor.longitude];
    [self.mapView addAnnotation:pointAnnotation];
}

- (void)setLocationWithLatitude:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)longitude{
     WEAKSELF
    //反编码 经纬度---->位置信息
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) {
            DDLogInfo(@"反编码失败:%@",error);
            [weakSelf.tableView reloadData];
        }else{
            //NSLog(@"反编码成功:%@",placemarks);
            CLPlacemark *placemark=[placemarks lastObject];
            NSDictionary *addressDic=placemark.addressDictionary;
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            NSString *name=[addressDic objectForKey:@"Name"];
            //NSLog(@"%@,%@,%@,%@",state,city,subLocality,street);
            NSString *strLocation;
            if (street.length == 0 || street == NULL || [street isEqualToString:@"(null)"]) {
                strLocation = [NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,name];
            }else{
                strLocation = [NSString stringWithFormat:@"%@%@%@%@%@",state,city,subLocality,street,name];
            }
            weakSelf.locationStr = strLocation;
            [weakSelf.rightButton setTitle:strLocation forState:UIControlStateNormal];
            [weakSelf.tableView reloadData];

        }
    }];
}


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }

    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.frame = CGRectMake(0, 0, 20, 24);
        annotationView.canShowCallout = YES;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
        annotationView.image = [UIImage imageNamed:@"point"];
        _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 0)];
        _rightButton.backgroundColor = [UIColor whiteColor];
        [_rightButton setTitleColor:Color_86898E forState:UIControlStateNormal];
        _rightButton.titleLabel.font = Font(14);
        _rightButton.titleLabel.numberOfLines = 0;
        annotationView.leftCalloutAccessoryView = _rightButton;
        return annotationView;
    }

    return nil;
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleArr.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        return 80;
    }else{
        return 60;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row > 0){
        KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
        if(indexPath.row == 1){
            cell.rightIcon.hidden = YES;
            cell.decLbl.text = self.locationStr;
        }else{
            cell.rightIcon.hidden = NO;
            if([_setInfo.ebike_set[@"fence_radius"] intValue] < 50){
                cell.decLbl.text = @"50公里";
            }else{
                cell.decLbl.text = [NSString stringWithFormat:@"%d公里",[_setInfo.ebike_set[@"fence_radius"] intValue] / 1000];
            }
        }
        cell.nameLbl.text = _titleArr[indexPath.row];
        return cell;
    }else{
        NewsSettingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsSettingsCell"];
        cell.titleLbl.text = _titleArr[indexPath.row];
        cell.decLbl.text = @"打开后将获取车辆位置,超出围栏设置范围后车辆将被锁定";
        cell.isOpenSwitch.on = [_setInfo.ebike_set[@"electronic_fence"] boolValue];
        cell.isOpenSwitch.tag = indexPath.row;
        [cell.isOpenSwitch addTarget:self action:@selector(isOpen:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(indexPath.row == 2){
        [[KRAlartManager shareInstance] showPickAlertView:[NSString stringWithFormat:@"围栏半径设置(%d公里)",[_setInfo.ebike_set[@"fence_radius"] intValue] / 1000] withcurrentIndex:[_setInfo.ebike_set[@"fence_radius"] intValue] IscanChooseHistory:NO  changeTitleBlock:^(NSString * _Nonnull title) {
            NSDictionary *dict = @{@"fence_radius":@([title intValue] * 1000)};
            NSDictionary *ebike_set = @{@"ebike_id":@(self.setId),@"ebike_set":dict};
            [self updateDeviceSettingforSet:nil andEbickSet:ebike_set];
        }];
    }
}

- (void)isOpen:(UISwitch *)sender{
    int type = 0;
    if(sender.on){
        if(self.lat > 0 && self.lng >0){
            type = 1;
            NSDictionary *dict = @{@"fence_center":@{@"lat":@(self.lat),@"lng":@(self.lng)}};
            NSDictionary *ebike_set = @{@"ebike_id":@(self.setId),@"ebike_set":dict};
            self.isUpdateLocation = YES;
            [self updateDeviceSettingforSet:nil andEbickSet:ebike_set];
        }else{
            [[KRAlartManager shareInstance] showAlert:@"车辆位置获取失败"];
            sender.on = NO;
        }
    }else{
        self.isUpdateLocation = NO;
    }
    NSDictionary *ebike_set = @{@"electronic_fence":@(type)};
    NSDictionary *dict = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"ebike_set":ebike_set};
    [self updateDeviceSetting:dict];


}

- (void)updateDeviceSetting:(NSDictionary *)dict{
    WEAKSELF
    [NetworkingTool POST:Device_setting_update parameters:dict isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf getDeviceSetting];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
    
}

- (void)updateDeviceSettingforSet:(NSDictionary *)deviceSet andEbickSet:(NSDictionary *)dcit{
    NSDictionary *parameters;
    if(deviceSet){
        parameters = deviceSet;
    }else{
        parameters = dcit;
    }
    WEAKSELF
    [NetworkingTool POST:Device_setting_update parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if(!weakSelf.isUpdateLocation){
            [weakSelf getDeviceSetting];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
   // Device_setting_update
}


- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRSettingCell" bundle:nil] forCellReuseIdentifier:@"KRSettingCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsSettingsCell" bundle:nil] forCellReuseIdentifier:@"NewsSettingsCell"];

        [self.view addSubview:_tableView];
    }
    return _tableView;
}



@end
